require 'digest/sha1'
class User < ActiveRecord::Base
  include AuthenticatedBase
  has_many :assets, :as => :attachable
  belongs_to :city
  has_one :latest_assignment,
     :class_name => 'Assignment',
     :order => 'created_at DESC'
  has_many :assignments
  has_many :projects
  has_many :assignments_issued, :class_name => 'Assignment', :through => :projects
  has_many :projects_participated_in, :class_name => 'Project', :through => :assignments

  validates_uniqueness_of :login, :email, :case_sensitive => false
  validates_presence_of :tname

  # Protect internal methods from mass-update.
  attr_accessible :login, :email, :password, :password_confirmation, :tname
  
  def available?
     available_at < Time.now and busy_at > Time.now
  end
  
  def bad?
     negex > 0
  end

  def level
     if posex == 0 then "(?)" elsif posex < 5 then "(.)" else "(!)" end
  end
  
  def count_ex(num)
     as_author = assignments_issued.find(:all, :conditions=>{ :experience => num }).size
     as_agent  = projects_participated_in.find(:all, :conditions => { :experience => num }).size
     return as_author + as_agent
  end
  
  def posex; return count_ex(1); end
  def negex; return count_ex(-1); end
  
  def to_param
    login
  end

  def self.find_by_param(*args)
    find_by_login *args
  end
    
end
